#include <iostream>
using namespace std;
#include <signal.h>
#include <sys/types.h>
#include <unistd.h>
#include <cerrno>

/* int cnt = 1;

void SIG2_handle(int sig){
    cout << getpid() << "进程" << "捕捉到了" << sig << "信号" << endl;
    cout << "cnt : " << cnt << endl;
    exit(errno);
} */





/* int main(){
    // 把所有的信号捕捉一下 -> 方便观察
    /* for(int i = 1; i < 32; ++i)
        signal(i, SIG2_handle); */

    /* cout << "hello" << endl;
    cout << "hello" << endl;
    cout << "hello" << endl;
    cout << "hello" << endl;
    cout << "hello" << endl;
    abort(); */


   /*  for(int i = 1; i < 32; ++i){
        if(i == 9 || i == 19) continue;
        //kill(getpid(), i);
        raise(i);
    } */

    /* while(1){
        cout << "我是一个进程, pid是: " << getpid() << endl;
        sleep(1);
    } */
    //return 0;

//}






/* int main(){
    for(int i = 1; i < 32; ++i)
        signal(i, SIG2_handle);

    //1. 除0错误
    /* cout << "hello" << endl;
    cout << "hello" << endl;
    cout << "hello" << endl;
    sleep(2);
    int a = 0;
    a /= 0; */
    


   /*  //2. 段错误
    int a = 10;
    int* pa = nullptr;
    *pa = 20;
    cout << *pa << endl; */
    //return 0;
//}

/* int cnt = 1;

void SIG2_handle(int sig){
    cout << getpid() << "进程" << "捕捉到了" << sig << "信号" << endl;
    cout << "cnt : " << cnt << endl;
    exit(errno);
}

int main(){
    for(int i = 1; i < 32; ++i)
        signal(i, SIG2_handle);

    //一秒钟后响，把所有信号也捕捉一下。
    alarm(1);
    while(1){
        //cout << "hello" << ", pid is " << getpid() << ", cnt : " << cnt << endl;
        ++cnt;
    }
    return 0;
} */

#include <functional>
#include <vector>

using func_t = function<void()>;
vector<func_t> _vf;

void CheckMem(){
    cout << "检查内存碎片..." << endl;
}

void Register(){
    cout << "注册..." << endl;
}

void Init(){
    cout << "初始化" << endl;
}


void SIG_handle(int sig){
    cout << getpid() << "进程" << "捕捉到了" << sig << "信号" << endl;
    alarm(1);// 重新设置闹钟
}

int main(){
    for(int i = 1; i < 32; ++i)
        signal(i, SIG_handle);

    _vf.push_back(Register);
    _vf.push_back(Init);
    _vf.push_back(CheckMem);

    alarm(1);
    while(1){
        pause();//阻塞 收到信号后就不会再阻塞
        for(auto& func : _vf){
            func();
        }
    }
    return 0;
}